package com.taotao.service.impl;

import java.io.IOException;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.pojo.PictureResult;
import com.taotao.common.util.FtpUtil;
import com.taotao.common.util.IDUtils;
import com.taotao.service.PictureService;

@Service("pictureService")
public class PictureServiceImpl implements PictureService {
	@Value("${FTP_IP}")
	private String FTP_IP;
	@Value("${FTP_PORT}")
	private int FTP_PORT;
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	@Value("${IMAGE_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Value("${IMAGE_BASE_URL}")
	private String FTP_BASE_URL;

	@Override
	public PictureResult uploadPic(MultipartFile uploadFile) {
		PictureResult result = new PictureResult(-1, "上传失败");
		try {
			// String oldName=uploadFile.getOriginalFilename();
			if (uploadFile != null) {
				String oldName = uploadFile.getOriginalFilename();
				String picPath = new DateTime().toString("/yyyyMM/dd/");
				if (oldName != null && oldName.indexOf(".") > 0) {
					String newName = IDUtils.genImageName() + oldName.substring(oldName.lastIndexOf("."));
					boolean b = FtpUtil.uploadFile(FTP_IP, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH, picPath, newName,
							uploadFile.getInputStream());
					if (b) {
						result = new PictureResult(0, FTP_BASE_URL + picPath + newName);
					}
				}
			}

		} catch (IOException e) {
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

}
